﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ZK.Common;

namespace ZK.HardWareBLL
{
    /// <summary>
    /// 上海耀华xk3190A9 
    /// 兼容 宁波柯力d2008
    /// </summary>
    public class FangzuobiyiBLL
    {
        SerialPort serialPort;
        HaredWareCommonM haredWareCommonM;

        private Socket listenSocket;
        List<Socket> clientsockets = new List<Socket>();
        double nowWeight;
        public FangzuobiyiBLL()
        {
            nowWeight = 0;
            serialPort = new SerialPort();
            haredWareCommonM = Common.IConfig.GetSetwagonBalance;
            Open();
        }
        public FangzuobiyiBLL(HaredWareCommonM hWC)
        {
            nowWeight = 0;
            serialPort = new SerialPort();
            haredWareCommonM = hWC;
            Open();
        }
      
        /// <summary>
        /// 关闭com
        /// </summary>
        public void close()
        {
            serialPort.Close();
            serialPort.Dispose();
            serialPort = null;
        }

        public void Open()
        {
            try
            {
                if (!serialPort.IsOpen)
                {
                    serialPort.PortName = haredWareCommonM.PortName;
                    serialPort.BaudRate = Convert.ToInt32(haredWareCommonM.BaudRate);
                    serialPort.Parity = haredWareCommonM.Parity;
                    serialPort.DataBits = Convert.ToInt32(haredWareCommonM.DataBits);
                    serialPort.StopBits = haredWareCommonM.StopBits;
                    //serialPort.ReadTimeout = 30;
                    //ComDevice.ReadBufferSize = 20;
                    //serialPort.ReceivedBytesThreshold = 50;
                    serialPort.Open();
                    serialPort.DataReceived += SerialPort_DataReceived;
                    // ComDevice.ErrorReceived += ComDevice_ErrorReceived;
                    //serialPort.ReceivedBytesThreshold = 50;
                    //serialPort.DtrEnable = true;
                }
            }
            catch (Exception ex)
            {

                Common.Log4.LogManage.WriteErr(ex.ToString());
                DelegateHelper.InfoMessageEvent?.Invoke(ex.Message);
            }
        }

        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(100);// 很关键，可以获取当前缓存区最全的数据         
            byte[] bytes = new byte[serialPort.BytesToRead];
            serialPort.Read(bytes, 0, serialPort.BytesToRead);
            DelegateHelper.A9Event?.Invoke(bytes);



            string hexStr = BitConverter.ToString(bytes).Replace("-","");
            DelegateHelper.A9EventStr?.Invoke(hexStr);
            //byte[] bbz = null;
            //for (int i = 0; i < bytes.Length; i++)
            //{
            //    if (bytes[i] == 2)
            //    {
            //        bbz = bytes.Skip(i).Take(18).ToArray();
            //        break;
            //    }

            //}

            //if (bbz != null)
            //{
            //    double weight = GetWeight(bbz); 
            //    //if ((weight != nowWeight) && (weight != -1))
            //    //{
            //    // nowWeight = weight;
            //    DelegateHelper.InfoMessageEvent?.Invoke(weight.ToString());
            //    // }
            //}
        }

        private double GetWeight(byte[] bytes)
        {
            // Common.Log4.LogManage.WriteInfo(string.Join("-", bytes));
            if (bytes.Length == 18 && (bytes[0] == 2) && (bytes[16] == 13))
            {
                var number = 0;
                number += bytes[5] > 32 ? (bytes[5] - 48) * 1000 : 0;
                number += bytes[6] > 32 ? (bytes[6] - 48) * 100 : 0;
                number += bytes[7] > 32 ? (bytes[7] - 48) * 10 : 0;
                number += bytes[8] > 32 ? (bytes[8] - 48) : 0;
                return (double)number / 100;
                //return number;
            }
            else
            {
                Common.Log4.LogManage.WriteErr("获取地磅数据长度有误 errDate:" + string.Join("-", bytes));
                return -1;
            }
        }

        ~FangzuobiyiBLL()
        {
            try
            {
                if (serialPort.IsOpen)
                {
                    serialPort.Close();
                }
            }
            catch (Exception ex)
            {

                Common.Log4.LogManage.WriteErr(ex.ToString());
            }
        }
    }
}
